package com.example.bitcoinnotificator;

import java.util.Timer;
import java.util.TimerTask;

import android.app.AlarmManager;
import android.app.IntentService;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.SystemClock;
import android.util.Log;
import android.widget.Toast;

public class CheckerService extends IntentService {
	public static final String TIME = "time_interval";
	public static final String MINVAL = "min_value";
	public static final String MAXVAL = "max_value";
	public static final String CURVALUE = "current_value";
	public static final String NOTIFICATION = "com.example.bitcoinnotificator.broadcast";
	public static final int RESULT_ALERT = 1;
	public static final int RESULT_OK = 0;
	private byte result = 0; // 0 - bitcoin value ok, 1 - bitcoin value outside borders
	private double value = 0; // current bitcoin value
	private double MinValue = 0;
	private double MaxValue = 1;
	private Timer timer;
	private MyTimerTask timerTask;
	
	private class MyTimerTask extends TimerTask 
	{
	     public void run()
	     { 
	    	 value = CurrencyDownloader.readValue("PLN", 10000);
	    	 
	    	 if ( value < MinValue || value > MaxValue )
	    		 broadcastAlert(value);
	     } 
	}
	
	public void shit(String s) {
		Toast.makeText(this, s, Toast.LENGTH_LONG).show();
	}
	
	public CheckerService() {
		super("BitCoin Checker Service");
		// TODO Auto-generated constructor stub
	}
	
	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		//super.onStartCommand(intent,flags,startId);
		Log.d("debug", "onStartCommand");
		return super.onStartCommand(intent,flags,startId);
	}

	@Override
	protected void onHandleIntent(Intent intent) {

		int TimeInSecs = intent.getIntExtra(TIME,1);
		MinValue = intent.getDoubleExtra(MINVAL,0);
		MaxValue = intent.getDoubleExtra(MAXVAL,1);
		
		Log.d("debug", "onHandleIntent");
		
	    performScheduledCheck(TimeInSecs*1000,MinValue,MaxValue);
	    while(true) { Log.d("dasda","petla"); SystemClock.sleep(5000);}
	}
	
	@Override
	public void onDestroy() {
		super.onDestroy();
		Log.d("debug", "onDestroy");
		if (timer != null) timer.cancel();
	}
	
	private void performScheduledCheck(long timeInterval, double minValue, double maxValue) {
		Log.d("adndz","krwarwa");
		timer = new Timer(); 
		timerTask = new MyTimerTask();
		timer.schedule ( timerTask, timeInterval, timeInterval );
	}
	
	private void broadcastAlert(double value) {
		Intent i = new Intent(NOTIFICATION);
		i.putExtra(CURVALUE, value);
		sendBroadcast(i);
	}

}
